# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import os
import sys
import threading
import time
from load_txt import get_txt_datas
from PyQt5 import uic
from PyQt5.QtCore import Qt, pyqtSignal, QThread
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog

#实现多线程，避免GUI界面卡顿

class MyThread(QThread):
    thread_signal = pyqtSignal(str)
    def __init__(self):
        super().__init__()
        self.txt_input = ''

    def run(self):
        msg = ''
        if self.txt_input.endswith('.log'):
            self.thread_signal.emit(msg+'【导入Log数据成功】')
            self.thread_signal.emit(msg + '【Begin to handle datas】')
            get_txt_datas(self.txt_input)
            self.thread_signal.emit(msg + '【Create file successfully!!!】')
            self.thread_signal.emit(msg + '【Please find in directory ./root  】')
            threads = []
        else:
            self.thread_signal.emit(msg + '【导入Log数据失败，请重试导入步骤】')

class MyWindow(QWidget):
    my_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.init_ui()
        self.cwd = os.getcwd()
        self.msg_history = list()

    def init_ui(self):
        self.ui = uic.loadUi("./UI/main.ui")
        self.msg=self.ui.label_2
        self.msg.setWordWrap(True)
        self.msg.setAlignment(Qt.AlignTop)

        #提取UI控件
        self.txt_input_qwidget=self.ui.lineEdit
        self.txt_upload_btn=self.ui.pushButton
        self.run_btn=self.ui.commandLinkButton
        self.scroll_qwidget=self.ui.scrollArea
        #绑定信号与槽函数
        self.txt_upload_btn.clicked.connect(self.upload_txt)
        self.run_btn.clicked.connect(self.start_thread)


    def upload_txt(self):
        file_path, filetype = QFileDialog.getOpenFileName(self, "选取文件", self.cwd,
                                                                "Log Files (*.log);;All Files (*)")
        if file_path == "":
            return

        self.txt_input_qwidget.setText(file_path)


    def start_thread(self):
        self.my_thread = MyThread()  # 创建线程
        self.my_thread.txt_input = self.txt_input_qwidget.text()
        self.msg_history = list()
        self.my_thread.thread_signal.connect(self.terminal_show)
        self.my_thread.start()  # 开始线程

    def terminal_show(self, msg):
        print(msg)
        self.msg_history.append(msg)
        self.msg.setText("<br>".join(self.msg_history))
        self.msg.resize(681, self.msg.frameSize().height() + 61)
        self.msg.repaint()

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MyWindow()
    w.ui.show()
    sys.exit(app.exec_())


# See PyCharm help at https://www.jetbrains.com/help/pycharm/
